package com.smartscreen.lifeserviceinfomanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smartscreen.lifeserviceinfomanage.dto.CanteenDetailDTO;
import com.smartscreen.lifeserviceinfomanage.dto.CanteenListDTO;
import com.smartscreen.lifeserviceinfomanage.entity.Canteen;
import com.smartscreen.lifeserviceinfomanage.entity.CanteenMenu;
import com.smartscreen.lifeserviceinfomanage.mapper.CanteenMapper;
import com.smartscreen.lifeserviceinfomanage.mapper.CanteenMenuMapper;
import com.smartscreen.lifeserviceinfomanage.service.CanteenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CanteenServiceImpl implements CanteenService {
    
    @Autowired
    private CanteenMapper canteenMapper;
    
    @Autowired
    private CanteenMenuMapper canteenMenuMapper;
    
    @Override
    public List<CanteenListDTO> getAllCanteens() {
        List<Canteen> canteens = canteenMapper.selectList(null);
        return canteens.stream().map(this::convertToListDTO).collect(Collectors.toList());
    }
    
    @Override
    public CanteenDetailDTO getCanteenDetail(String canteenId) {
        Canteen canteen = canteenMapper.selectOne(new QueryWrapper<Canteen>().eq("canteen_id", canteenId));
        if (canteen == null) {
            return null;
        }
        
        List<CanteenMenu> menus = canteenMenuMapper.selectList(new QueryWrapper<CanteenMenu>().eq("canteen_id", canteenId));
        
        return convertToDetailDTO(canteen, menus);
    }
    
    private CanteenListDTO convertToListDTO(Canteen canteen) {
        CanteenListDTO dto = new CanteenListDTO();
        dto.setCanteenId(canteen.getCanteenId());
        dto.setName(canteen.getName());
        dto.setLocation(canteen.getLocation());
        return dto;
    }
    
    private CanteenDetailDTO convertToDetailDTO(Canteen canteen, List<CanteenMenu> menus) {
        CanteenDetailDTO dto = new CanteenDetailDTO();
        dto.setName(canteen.getName());
        
        CanteenDetailDTO.BusinessHoursDTO businessHours = new CanteenDetailDTO.BusinessHoursDTO();
        businessHours.setBreakfast(canteen.getBreakfastHours());
        businessHours.setLunch(canteen.getLunchHours());
        businessHours.setDinner(canteen.getDinnerHours());
        dto.setBusinessHours(businessHours);
        
        List<CanteenDetailDTO.MenuDTO> menuDTOs = menus.stream().map(menu -> {
            CanteenDetailDTO.MenuDTO menuDTO = new CanteenDetailDTO.MenuDTO();
            menuDTO.setWindowName(menu.getWindowName());
            menuDTO.setDishes(Arrays.asList(menu.getDishes().split(",")));
            return menuDTO;
        }).collect(Collectors.toList());
        dto.setMenu(menuDTOs);
        
        return dto;
    }
}